/** 全局toast 提示 */
import React, { useEffect, useRef } from 'react';
import { StyleSheet, Text, Animated } from "react-native";
import { getColorStr } from "../themes";
import { useGlobalStore } from "../mobx";
import { observer } from "mobx-react-lite";
import { dpw10, dpw12, dpw16, dpw24, dpw8 } from "../constants";
import { t } from "../utils";

export const Toast = observer(() => {
    const { theme, language, toastKey, changeToastKey } = useGlobalStore()
    const fadeAnim = useRef(new Animated.Value(0)).current
    
    useEffect(() => {
        if (toastKey) {
            Animated.timing(fadeAnim, {
                toValue: 1,
                duration: 500,
                useNativeDriver: true
            }).start(() => {
                let timer: any = setTimeout(() => {
                    Animated.timing(fadeAnim, {
                        toValue: 0,
                        duration: 500,
                        useNativeDriver: true
                    }).start(() => {
                        changeToastKey('')
                        clearTimeout(timer)
                        timer = null
                    })
                }, 1000)
            })
        }
    }, [toastKey])
    
    if (!toastKey) return null
    
    return (
        <Animated.View style={[StyleSheet.absoluteFillObject, styles.contail, { opacity: fadeAnim }]}>
            <Text
                style={{
                    ...styles.text,
                    backgroundColor: getColorStr(theme, 'color_41'),
                    color: getColorStr(theme, 'color_2'),
                }}
            >
                {t(language, toastKey)}
            </Text>
        </Animated.View>
    ) 
})
 
const styles = StyleSheet.create({
    contail: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    text: {
        paddingHorizontal: dpw12,
        paddingVertical: dpw10,
        borderRadius: dpw8,
        fontSize: dpw16,
        lineHeight: dpw24,
    }
});
